package com.robusta.cityuate.services;

import java.io.UnsupportedEncodingException;

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;

import com.robusta.cityuate.objects.Reservation;
import com.robusta.cityuate.utils.ConnectionUtils;

public class CheckInOutService extends HTTPService {

	private static final String REQUEST_URL = "/reservations/";
	private Context mContext = this;
	public final static String IS_CHECK_IN = "isCheckin";
	private boolean isCheckIn = false;
	public final static String CHECK_IN = "/check_in";
	public final static String CHECK_OUT = "/check_out";
	public Reservation reservation;

	@Override
	protected void onResponse() {
		Intent reportSpotUIupdate = new Intent(assignedFilter);
		switch (responseStatusCode) {
		case HttpStatus.SC_NO_CONTENT: {
			// remove connection from shared pref
			ConnectionUtils.setDisconnecting(mContext, true, assignedFilter,
					null);
			// update UI if active
			reportSpotUIupdate.putExtra(RESUlT, true);
			sendOrderedBroadcast(reportSpotUIupdate, null);
			if (isCheckIn)
				{Reservation.saveReservation(mContext, reservation);
				ScheduledNotifications.scheduleNotification(mContext, reservation);
				}
			else
				{Reservation.removeReservation(mContext);
				ScheduledNotifications.cancelScheduledNotification(mContext, reservation);
				}
			return;
		}
		case HttpStatus.SC_NOT_FOUND:
		case HttpStatus.SC_UNAUTHORIZED: {
			JSONObject res;
			try {
				res = new JSONObject(responseString);
				onNoResponse(res.getString(MESSAGE));
			} catch (JSONException e) {
				onNoResponse(UNKNOWN_RESPONSE);
			}
			break;
		}
		default:
			onNoResponse(UNKNOWN_RESPONSE);
		}

	}

	@Override
	protected void onNoResponse(String msg) {
		// remove connection from shared pref keeping result and reason
		ConnectionUtils.setDisconnecting(mContext, false, assignedFilter, msg);
		// update UI if active
		Intent reportSpotUIupdate = new Intent(assignedFilter);
		reportSpotUIupdate.putExtra(RESUlT, false);
		sendOrderedBroadcast(reportSpotUIupdate, null);

	}

	@Override
	protected HttpRequestBase initRequest() {
		reservation = (Reservation) extras
				.getSerializable(Reservation.RESERVATION);
		isCheckIn = extras.getBoolean(IS_CHECK_IN);
		HttpPut req = new HttpPut(API_URL + REQUEST_URL
				+ reservation.getId()
				+ ((isCheckIn) ? CHECK_IN : CHECK_OUT));
		try {
			req.setEntity(new ByteArrayEntity(("").getBytes("UTF-8")));
		} catch (UnsupportedEncodingException e) {
		}
		return req;
	}

}
